package nowercoder.basics.exce01;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * 比较器的使用
 * 通过实现Comparator 的 compare 方法
 * 进行自主的比较器定义，适用于自定义的对象间的互相比较。
 */
public class Comparator_Demo {

    public static void main(String[] args) {
        Student s1 = new Student("jjx", 001, 21);
        Student s2 = new Student("ysy", 002, 20);
        Student s3 = new Student("jxy", 003, 14);

        Student[] students = {s1, s2, s3};
        for (int i = 0; i < students.length; i++) {
            System.out.println(students[i]);
        }

        System.out.println("----------------------");
        Arrays.sort(students, new IdDescendingComparator());
        for (Student stu : students) {
            System.out.println(stu);
        }

        System.out.println("-----------------------");
        Arrays.sort(students, new AgeAscendingComparator());
        for (Student stu : students) {
            System.out.println(stu);
        }

        System.out.println("------------------------");
        System.out.println("使用优先级队列实现的排序：（按 age 降序排列）");
        PriorityQueue<Student> heap = new PriorityQueue<>(new AgeDescendingComparator());
        heap.add(s1);
        heap.add(s2);
        heap.add(s3);
        while (!heap.isEmpty()) {
            Student student = heap.poll();
            System.out.println(student);
        }
    }
}

/**
 * 定义了四种比较规则
 * compara 方法中的返回值 分三种情况：
 * 1. -1 （小于0） 第一个数小于第二个数
 * 2. 0 （等于0） 第一个数和第二个数相等
 * 3. 1 （大于0 ） 第一个数大于第二个数
 */
class IdAscendingComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.id - o2.id;
    }
}

class IdDescendingComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o2.id - o1.id;
    }
}

class AgeAscendingComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

class AgeDescendingComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o2.age - o1.age;
    }
}

/**
 * 自定义的数据类型
 * 将要实现排序的对象
 */
class Student {
    String name;
    int id;
    int age;

    public Student() {
    }

    public Student(String name, int id, int age) {
        this.name = name;
        this.id = id;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", age=" + age +
                '}';
    }
}
